﻿Imports Llama
Imports Telerik.WinControls.UI
Imports SPF.Client.Administration
Imports SPF.Client
Imports SPF.Client.Schema.Collection
Imports System.Xml
Imports SPF.Client.Schema.Interface
Imports System.Text.RegularExpressions

Module Module1

    Public DS As LMADataSource
    Public objPlantSettings As LMPlantSettings
    Public objOptionSettings As LMOptionSettings

    Public MyPIDConn As New DBConn.PIDDBConn

    Public CallResult As String
    Public SelectStr As String
    ''' <summary>
    ''' Plant Structure的根目录
    ''' </summary>
    Public strPlantPath As String
    ''' <summary>
    ''' 保温文件InsulationSpec.isl的路径
    ''' </summary>
    Public sInsulFilePath As String
    ''' <summary>
    ''' 当前plant注册到的SPF的地址
    ''' </summary>
    Public strSPFURL As String
    ''' <summary>
    ''' PAU最大的层级，从0开始
    ''' </summary>
    Public MaxDepth As String
    ''' <summary>
    ''' 存储一个图纸对象的ID，方便查询图纸的所有属性。
    ''' </summary>
    Public ConstDrawingID As String = ""

    Public dtCreate As New DataTable
    ''' <summary>
    ''' 图纸ID的集合
    ''' </summary>
    Public DrawingCol As New ArrayList
    ''' <summary>
    ''' UNIT的集合，节点的Name
    ''' </summary>
    ''' <remarks></remarks>
    Public UnitCol As New ArrayList

    ''' <summary>
    ''' 分析xml文件时，得到的根Node
    ''' </summary>
    ''' <remarks></remarks>
    Public oRootNode As XmlNode

    Public MySPFConn As SPFConnection
    Public MySPFServer As SPFServer
    Public MySPFSession As SPFSession
    Public MySPFWindowsClient As New SPFWindowsClient

    Public sSpfUser As String : Public sSpfPs As String : Public blnIWA As Boolean





    ''' <summary>
    ''' 用于拿pid的从api获得的数据。因为老因为dbnull的关系，导致直接tostring会报错
    ''' </summary>
    ''' <param name="x"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function GetAPIValue(x As Object) As String
        If x Is Nothing Then
            Return ""
        ElseIf IsDBNull(x) Then
            Return ""
        ElseIf x Is DBNull.Value Then
            Return ""
        Else

            Return x

        End If
    End Function
    ''' <summary>
    ''' mode 1，用llama方式,返回LMDrawings对象。
    ''' mode 2，用dwgid方式，返回'A','B'这样的字符串
    ''' </summary>
    Public Sub GetDwgCol(ByRef ds As LMADataSource, ByRef DrawingCol As ArrayList, ByRef DwgIDs As String)
        DrawingCol.Clear()
        LoopTreeNode(RadForm1.RadTreeView1.Nodes.Item(0), DrawingCol, UnitCol)   '遍历mainform下的图纸目录树，将勾选的图纸的ID，加入到DrawingCol这个集合里

        For i = 0 To DrawingCol.Count - 1
            DwgIDs = DwgIDs + "'" + DrawingCol.Item(i).ToString + "',"
        Next
        If DwgIDs <> "" Then
            DwgIDs = Mid(DwgIDs, 1, Len(DwgIDs) - 1) '去最后的逗号
        End If

    End Sub
    ''' <summary>
    ''' 填充objDrawings
    ''' </summary>
    ''' <param name="ds"></param>
    ''' <param name="DrawingCol"></param>
    ''' <param name="objDrawings"></param>
    Public Sub GetDwgCol(ByRef ds As LMADataSource, ByRef DrawingCol As ArrayList, ByRef objDrawings As LMDrawings)
        DrawingCol.Clear()
        LoopTreeNode(RadForm1.RadTreeView1.Nodes.Item(0), DrawingCol, UnitCol)   '遍历mainform下的图纸目录树，将勾选的图纸的ID，加入到DrawingCol这个集合里
        Try
            For i = 0 To DrawingCol.Count - 1
                objDrawings.Add(ds.GetDrawing(DrawingCol.Item(i).ToString))
            Next
        Catch ex As Exception
            MessageBox.Show("需要重启下工具。")
            Application.Exit()
        End Try

    End Sub


    ''' <summary>
    ''' 遍历图纸目录树，将勾选的图纸，加入到DrawingCol这个集合里
    ''' </summary>
    ''' <param name="xxxnode"></param>
    Public Sub LoopTreeNode(xxxnode As RadTreeNode, ByRef DrawingCol As ArrayList, ByRef UnitCol As ArrayList)

        If xxxnode.Level = MaxDepth And xxxnode.Checked = True Then   'UNIT节点
            UnitCol.Add(xxxnode.Name)
        End If
        If xxxnode.Nodes.Count <> 0 Then   '子节点的数目
            For Each xxxNodeChild As RadTreeNode In xxxnode.Nodes
                LoopTreeNode(xxxNodeChild, DrawingCol, UnitCol)   '迭代
            Next
        ElseIf xxxnode.Level = MaxDepth + 1 And xxxnode.Checked = True Then
            '没有子节点了，即到了图纸，或者说到了一个没有图纸的unit
            DrawingCol.Add(xxxnode.Name)    '这里的Name，即nodes.ADD时候的Key    即  DRAWING  ID
        End If
    End Sub

    Public Function SetDisplaySet(Flag As Boolean)

        Dim pidAutoApp As InteropPidAuto.Application
        pidAutoApp = New InteropPidAuto.Application
        Dim displaySets As InteropIDisplaySetinf.ISPDisplaySets
        displaySets = pidAutoApp.ActiveDrawing.ViewDisplaySets
        Dim dispSet As InteropIDisplaySetinf.ISPDisplaySet
        dispSet = displaySets.Item(3)
        If Flag = True Then
            pidAutoApp.ActiveDrawing.ApplyDisplaySet(dispSet)
        ElseIf Flag = False Then
            pidAutoApp.ActiveDrawing.ClearDisplaySet()
        End If
        pidAutoApp.ClearAll()

    End Function


    ''' <summary>
    ''' 查询一个对象的属性
    ''' </summary>
    ''' <param name="LLAMAObj"></param>
    ''' <param name="ItemType"></param>
    ''' <returns></returns>
    Public Function LoopItemAtts(LLAMAObj As Object, ItemType As String) As ArrayList
        Dim al As ArrayList = New ArrayList
        For Each objAttrInLoop As LMAAttribute In LLAMAObj.Attributes
            Dim objAttr As LMAAttribute = objAttrInLoop
            If objAttrInLoop.Name = "SP_ID" Or objAttrInLoop.Name = "Name" Or objAttrInLoop.Name = "Path" Then
                '排除默认的3个属性列
            Else
                Try
                    If IsNothing(objAttrInLoop.ISPAttribute.Attribution.ISPEnumAtts) Then
                        Throw New Exception("非列表属性")
                    End If
                    If objAttrInLoop.ISPAttribute.Attribution.ISPEnumAtts.Count > 0 And objAttrInLoop.ISPAttribute.Attribution.ReadOnlyMask = 0 Then  '0是可以修改，3是不行

                        al.Add(objAttrInLoop.ISPAttribute.Attribution.DisplayName +
                               "                                                                                                         |       " +
                               objAttr.Name + "@")
                        '代表属性为select list
                    Else
                        'select list,but readonly
                        al.Add(objAttrInLoop.ISPAttribute.Attribution.DisplayName +
                               "                                                                                                         |       " +
                               objAttr.Name)
                    End If
                Catch ex As Exception
                    'no select list
                    al.Add(objAttrInLoop.ISPAttribute.Attribution.DisplayName +
                           "                                                                                                         |       " +
                           objAttr.Name)
                End Try


            End If
        Next
        al.Sort()
        Return al
    End Function

    ''' <summary>
    ''' 加载drawing到左侧的tree
    ''' </summary>
    ''' <param name="IfInitial">表示是否是第一次</param>
    Public Sub LoadDrawing(IfInitial As Boolean)

        If IfInitial Then

            Dim MyTree As RadTreeView = RadForm1.RadTreeView1
            MyTree.Nodes.Clear()

            Dim al As ArrayList = New ArrayList

            Dim ParentNode As New RadTreeNode

            SelectStr = <string>
select t.sp_id,t.name,t.depth,t.parentid,t2.name ParentName 
from xxxSchemaName.T_PLANTGROUP t
left join xxxSchemaName.T_PLANTGROUP t2 on t.parentid=t2.sp_id
order by t.depth,t.name
                    </string>.Value  '查询plantgroup
            dtCreate.Reset()
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.PIDPlant_User, SelectStr, dtCreate)
            SelectStr = <string>
select T.SP_ID,T.NAME,T.SP_PLANTGROUPID 
from xxxSchemaName.t_drawing T
order by t.name
                    </string>.Value
            Dim dtCreatePID As New DataTable
            MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, SelectStr, dtCreatePID)
            MyTree.Nodes.Add(dtCreate(0)("SP_ID").ToString, dtCreate(0)("Name").ToString, "")   '增加root 节点，即plant。key（name）就是spid。显示的是Name

            MaxDepth = dtCreate(dtCreate.Rows.Count - 1)("depth")

            For i = 1 To dtCreate.Rows.Count - 1    '从第二行开始，因为第一行肯定是当前plant的name
                If dtCreate(i)("depth") <> dtCreate(i - 1)("depth") Or dtCreate(i)("PARENTID") <> dtCreate(i - 1)("PARENTID") Then
                    'level有变化
                    For Each NodeFound As RadTreeNode In MyTree.FindNodes(dtCreate(i)("ParentName"))   '找到Parent节点
                        If NodeFound.Name = dtCreate(i)("parentid").ToString() Then
                            ParentNode = NodeFound
                            ParentNode.Nodes.Add(dtCreate(i)("SP_ID"), dtCreate(i)("Name"), "")   '在父节点下增加
                            Continue For
                        End If
                    Next
                Else
                    'level无变化
                    ParentNode.Nodes.Add(dtCreate(i)("SP_ID"), dtCreate(i)("Name"), "")  '在父节点下增加
                End If

                If dtCreate(i)("depth") = MaxDepth Then   '一般是Unit，即图纸所在的level
                    For Each dtFound As DataRow In dtCreatePID.Select("SP_PLANTGROUPID='" & dtCreate(i)("SP_ID") & "'")
                        '在drawings，过滤出该unit下的drawings
                        ParentNode.LastNode.Nodes.Add(dtFound("SP_ID"), dtFound("NAME"), "")    '图纸所在的unit，肯定是刚才建立的最后一个。比如area下的最后一个节点
                    Next
                End If
            Next
            If dtCreatePID.Rows.Count > 0 Then
                ConstDrawingID = dtCreatePID(0)("SP_ID")
            Else
                ConstDrawingID = ""
            End If




            'al = Nothing
        Else
            '            DrawingList.TreeView1.ShowLines = True

            '            Dim al As ArrayList = New ArrayList

            '            'objPlantGroups = New LMPlantGroups

            '            '类似于Drawing Manager的结构
            '            '***************  190719 尝试sql **********
            '            Dim ParentNode As TreeNode

            '            SelectStr = <string>
            'select t.sp_id,t.name,t.depth,t.parentid,t2.name ParentName 
            'from xxxSchemaName.T_PLANTGROUP t
            'left join xxxSchemaName.T_PLANTGROUP t2 on t.parentid=t2.sp_id
            'order by t.depth,t.name
            '                    </string>.Value
            '            PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantUser, SelectStr, dtCreate)    '查询plantgroup

            '            SelectStr = <string>
            'select T.SP_ID,T.NAME,T.SP_PLANTGROUPID 
            'from xxxSchemaName.t_drawing T
            'order by t.name
            '                    </string>.Value
            '            PIDReadDataByDBA(ActivePlantServer, PlantDBSystemUser, PlantDBSystemUserPS, Plant_DBNAME, ActivePlantPIDAppUser, SelectStr, dtCreatePID)   '查询drawings

            '            'DrawingList.TreeView1.Nodes.Add(dtCreate(0)("SP_ID"), dtCreate(0)("Name"))   '增加root 节点，即plant'
            '            MaxDepth = dtCreate(dtCreate.Rows.Count - 1)("depth")
            '            Try
            '                For i = 1 To dtCreate.Rows.Count - 1    '从第二行开始，因为第一行肯定是当前plant的name
            '                    If dtCreate(i)("depth") <> dtCreate(i - 1)("depth") Or dtCreate(i)("PARENTID") <> dtCreate(i - 1)("PARENTID") Then
            '                        'level有变化
            '                        For Each NodeFound As TreeNode In DrawingList.TreeView1.Nodes.Find(dtCreate(i)("ParentID"), True)    '找到Parent节点
            '                            ParentNode = NodeFound
            '                            'ParentNode.Nodes.Add(dtCreate(i)("SP_ID"), dtCreate(i)("Name"))   '在父节点下增加
            '                        Next
            '                    Else
            '                        'level无变化
            '                        'ParentNode.Nodes.Add(dtCreate(i)("SP_ID"), dtCreate(i)("Name"))  '在父节点下增加
            '                    End If

            '                    If dtCreate(i)("depth") = MaxDepth Then   '一般是Unit，即图纸所在的level
            '                        For Each NodeFound As TreeNode In DrawingList.TreeView1.Nodes.Find(dtCreate(i)("SP_ID"), True)    '找到Unit节点
            '                            ParentNode = NodeFound
            '                            Exit For
            '                        Next
            '                        'delete
            '                        Dim IfFound As Boolean = False
            '                        For Each NodeFound As TreeNode In ParentNode.Nodes
            '                            For Each dtFound As DataRow In dtCreatePID.Select("SP_ID='" & NodeFound.Name & "'")
            '                                IfFound = True
            '                                'modify
            '                                NodeFound.Text = dtFound("Name")
            '                            Next
            '                            '在数据库中图纸没找到，即被删了
            '                            If IfFound Then
            '                            Else
            '                                NodeFound.Remove()
            '                            End If
            '                        Next


            '                        'add
            '                        For Each dtFound As DataRow In dtCreatePID.Select("SP_PLANTGROUPID='" & dtCreate(i)("SP_ID") & "'")
            '                            '在drawings，过滤出该unit下的drawings
            '                            If ParentNode.Nodes.Find(dtFound("SP_ID"), True).Count = 0 Then
            '                                '图纸没找到，即新的
            '                                ParentNode.Nodes.Add(dtFound("SP_ID"), dtFound("NAME"))   '但是这样只是插入在最后，不是排序的
            '                            End If
            '                        Next


            '                    End If
            '                Next
            '                Try
            '                    ConstDrawingID = dtCreatePID(0)("SP_ID")
            '                Catch ex As Exception

            '                End Try

            '            Catch ex As Exception

            '            End Try
            '            al = Nothing
        End If
        With RadForm1.RadTreeView1
            .ShowLines = True
            .ShowNodeToolTips = False
            .SortOrder = SortOrder.Ascending
            .CheckBoxes = True
            '.ShowExpandCollapse = True
            '.TriStateMode = True
        End With

        'objPlantGroups = Nothing
    End Sub


    ''' <summary>
    ''' 查询OptionManager相关的值
    ''' </summary>
    ''' <param name="OptionKey"></param>
    ''' <returns></returns>
    Public Function FindInfoInOptionManager(OptionKey As String) As String
        objOptionSettings = New LMOptionSettings
        objOptionSettings.Collect(DS)
        For Each objOptionSetting As LMOptionSetting In objOptionSettings
            If objOptionSetting.Attributes("Name").Value = OptionKey Then
                Return objOptionSetting.Attributes("Value").Value.ToString
                Exit For   '减少循环
            End If
        Next
        Return "Error"
    End Function
    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="OptionKey"></param>
    ''' <returns></returns>
    Public Function FindInfoInPlantSetting(OptionKey As String) As String
        objPlantSettings = New LMPlantSettings
        objPlantSettings.Collect(DS)
        For Each objPlantSetting As LMPlantSetting In objPlantSettings
            If objPlantSetting.Attributes("Name").Value = OptionKey Then
                Return objPlantSetting.Attributes("Value").Value.ToString
                Exit For   '减少循环
            End If
        Next
        Return "Error"
    End Function

    Public Sub Writelog(msg As String, mode As String)
        Dim obj As Object = New Object
        Try

            Dim logPosition As String = sInsulFilePath.Replace("InsulationSpec.isl", "SNECLog\" + mode + "Log - " + Environment.UserName + ".log")




            SyncLock (obj)
                Using file As System.IO.StreamWriter = New System.IO.StreamWriter(logPosition, True)  '若不存在 会 自动 创建一个。但是上级文件夹需要有
                    file.WriteLine(DateTime.Now.ToLocalTime().ToString())
                    file.WriteLine(msg + Environment.NewLine)
                    file.Close()
                End Using
            End SyncLock

        Catch ex As Exception
            '免得文件夹路径没有而报错
        End Try
        obj = Nothing
    End Sub

    ''' <summary>
    ''' 读取反向数据流的xml，查出来对应spf的接口和属性。或者查enummap
    ''' </summary>
    ''' <param name="sNode">xml中的类型节点</param>
    ''' <param name="sSubNode">节点下的属性节点，如果是enum，则是代表enumMap节点</param>
    ''' <param name="SPIEnumValue">可选，enum的列表值</param>
    ''' <returns>返回查询到的值。如果是enum，则返回对应的pid里的symbol路径</returns>
    ''' <remarks></remarks>
    Public Function GetStrFromXml(ByRef oRootNode As XmlNode, sNode As String, sSubNode As String, Optional SPIEnumValue As String = "") As String
        Dim oNode As XmlNode
        Dim oSubNode As XmlNode
        oNode = oRootNode.SelectSingleNode(sNode)
        If IsNothing(oNode) Then
            Return "Error"
        Else
            If sSubNode = "Enum" Then
                '枚举值
                oSubNode = oNode.SelectSingleNode("EnumMap")
                If IsNothing(oNode) Then
                    Return "Error"
                Else
                    Dim oEnumNode As XmlNode
                    oEnumNode = oSubNode.SelectSingleNode("Type[@SPI='" & SPIEnumValue & "']")
                    If IsNothing(oEnumNode) Then
                        Return "Error"
                    Else
                        Return oEnumNode.Attributes("PID").Value
                    End If
                End If
            Else
                '普通的
                oSubNode = oNode.SelectSingleNode(sSubNode)
                If IsNothing(oNode) Then
                    Return "Error"
                Else
                    Return oSubNode.Attributes("SPI").Value
                End If
            End If
        End If
    End Function

    Public Function GetSPFPropValue(ByRef obj As IObject, InterfaceName_PropertyName As String, split As String) As String
        Dim sInterface As String : Dim SPROP As String
        Dim pos As Integer = InStr(InterfaceName_PropertyName, split)
        If pos = 0 Then
            '格式不是接口+属性
            Return "Error"
        Else
            sInterface = Mid(InterfaceName_PropertyName, 1, pos - 1)
            SPROP = Mid(InterfaceName_PropertyName, pos + 1)
            If Not IsNothing(obj.Interfaces(sInterface).Properties(SPROP)) Then

                Return obj.Interfaces(sInterface).Properties(SPROP).DisplayValue


            End If
            Return "Null"
        End If


    End Function

End Module
